package account

import (
  "fmt"
  "gitee.com/yizhisamoye/GoWeChat/utils"
  "io/ioutil"
  "net/http"
  "net/url"
  "os"
)
/**
二维码管理
*/
//创建临时二维码
func(w WxAccount)CreateQRScene(sceneId int,expireSeconds ...int)(map[string]interface{},error){
  return w.createQr("QR_SCENE",sceneId,"",expireSeconds...)
}
//创建临时二维码
func(w WxAccount)CreateQRStrScene(sceneStr string,expireSeconds ...int)(map[string]interface{},error){
  return w.createQr("QR_STR_SCENE",-1,sceneStr,expireSeconds...)
}
//创建永久二维码
func(w WxAccount)CreateQRLimitScene(sceneId int,expireSeconds ...int)(map[string]interface{},error){
  return w.createQr("QR_LIMIT_SCENE",sceneId,"",expireSeconds...)
}
//创建永久二维码
func(w WxAccount)CreateQRLimitStrScene(sceneStr string,expireSeconds ...int)(map[string]interface{},error){
  return w.createQr("QR_LIMIT_STR_SCENE",-1,sceneStr,expireSeconds...)
}
//创建二维码
func(w WxAccount)createQr(actionName string,sceneId int,sceneStr string,expireSeconds ...int)(map[string]interface{},error){
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/qrcode/create?access_token=%s",w.accessToken)
  et:=30
  if len(expireSeconds)>0&&expireSeconds[0]>0{
    if expireSeconds[0]>2592000{
      et=2592000
    }else{
      et=expireSeconds[0]
    }
  }
  data:=make(map[string]interface{})
  data["expire_seconds"]=et
  data["action_name"]=actionName
  if sceneStr!=""{
    data["action_info"]=map[string]interface{}{
      "scene":map[string]string{
        "scene_str":sceneStr,
      },
    }
  }else{
    data["action_info"]=map[string]interface{}{
      "scene":map[string]int{
        "scene_id":sceneId,
      },
    }
  }
  return utils.SendJson(url,data)
}
//将ticket转化为img
func(w WxAccount)TicketToQrCodeImgFile(ticket string)(*os.File,error){
  imgBytes,err:=w.TicketToQrCodeImgByte(ticket)
  if err!=nil{
    return nil,err
  }
  fileName:="qr_"+ticket+".jpg"
  file,err:=os.OpenFile("./temp/"+fileName,os.O_RDWR|os.O_CREATE,777)
  defer file.Close()
  if err!=nil{
    return nil,err
  }
  file.Write(imgBytes)
  return file,nil
}
func(w WxAccount)TicketToQrCodeImgByte(ticket string)([]byte,error){
  fetchUrl:=fmt.Sprintf("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s",url.QueryEscape(ticket))
  resp,err:=http.Get(fetchUrl)
  if err!=nil{
    return nil,err
  }
  return ioutil.ReadAll(resp.Body)
}
